const { Address, User } = require('../models');
const { Op } = require('sequelize'); // 添加这一行

// 获取用户的所有地址
exports.getUserAddresses = async (req, res, next) => {
    try {
        const userId = req.user.id;
        
        const addresses = await Address.findAll({
            where: { userId },
            order: [['isDefault', 'DESC'], ['createdAt', 'DESC']]
        });

        res.json({
            success: true,
            data: addresses
        });
    } catch (error) {
        next(error);
    }
};

// 创建新地址
exports.createAddress = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { name, phone, province, city, district, detail, isDefault } = req.body;

        // 如果设置为默认地址，先将其他地址设为非默认
        if (isDefault) {
            await Address.update(
                { isDefault: false },
                { where: { userId } }
            );
        }

        const address = await Address.create({
            userId,
            name,
            phone,
            province,
            city,
            district,
            detail,
            isDefault: isDefault || false
        });

        res.status(201).json({
            success: true,
            message: '地址创建成功',
            data: address
        });
    } catch (error) {
        next(error);
    }
};

// 更新地址
exports.updateAddress = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { id } = req.params;
        const { name, phone, province, city, district, detail, isDefault } = req.body;

        const address = await Address.findOne({
            where: { id, userId }
        });

        if (!address) {
            return res.status(404).json({
                success: false,
                message: '地址不存在'
            });
        }

        // 如果设置为默认地址，先将其他地址设为非默认
        if (isDefault) {
            await Address.update(
                { isDefault: false },
                { where: { userId } }
            );
        }

        await address.update({
            name,
            phone,
            province,
            city,
            district,
            detail,
            isDefault: isDefault !== undefined ? isDefault : address.isDefault
        });

        res.json({
            success: true,
            message: '地址更新成功',
            data: address
        });
    } catch (error) {
        next(error);
    }
};

// 删除地址
exports.deleteAddress = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { id } = req.params;

        const address = await Address.findOne({
            where: { id, userId }
        });

        if (!address) {
            return res.status(404).json({
                success: false,
                message: '地址不存在'
            });
        }

        // 如果删除的是默认地址，设置另一个地址为默认（如果有其他地址）
        if (address.isDefault) {
            const otherAddress = await Address.findOne({
                where: { userId, id: { [Op.ne]: id } }
            });
            
            if (otherAddress) {
                await otherAddress.update({ isDefault: true });
            }
        }

        await address.destroy();

        res.json({
            success: true,
            message: '地址删除成功'
        });
    } catch (error) {
        next(error);
    }
};

// 设置默认地址
exports.setDefaultAddress = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { id } = req.params;

        // 先将所有地址设为非默认
        await Address.update(
            { isDefault: false },
            { where: { userId } }
        );

        // 设置指定地址为默认
        const address = await Address.findOne({
            where: { id, userId }
        });

        if (!address) {
            return res.status(404).json({
                success: false,
                message: '地址不存在'
            });
        }

        await address.update({ isDefault: true });

        res.json({
            success: true,
            message: '默认地址设置成功',
            data: address
        });
    } catch (error) {
        next(error);
    }
};